import React, { Component } from "react";
import { deepFullCopy, messages } from "share/common";
import { Checkbox, Form, message, Modal, Radio } from "antd";
import { ImageUpload } from "components/index";
import config from "config";
import { connect } from "react-redux";
import { Home } from "../../home";
import DAService from "../../dashboard-admin.service";
import BaseService from "share/base.service";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

class EditTenantInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsShow: false,
      uploadedImages: [], //已经上传的logo
      showCustomLogo: false, //是否显示自定义的logo
      supportedLanguages: deepFullCopy(
        (props.tenant.tenantLanguageDTO && props.tenant.tenantLanguageDTO.supportedLanguages) || []
      ),
      defaultLanguage: (props.tenant.tenantLanguageDTO && props.tenant.tenantLanguageDTO.defaultLanguage) || {},
    };
  }

  componentWillMount() {}

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {}

  showSetModal = () => {
    const { tenant } = this.props;
    const defaultLanguage = tenant.tenantLanguageDTO ? tenant.tenantLanguageDTO.defaultLanguage : {};
    const supportedLanguages = deepFullCopy(
      tenant.tenantLanguageDTO ? tenant.tenantLanguageDTO.supportedLanguages : []
    );
    this.setState(
      {
        supportedLanguages,
        defaultLanguage,
        modalIsShow: true,
      },
      () => {
        this.setLogoImages();
      }
    );
  };

  getUploadedImage = (data) => {
    let uploadedImage = null;
    if (data.logoURL) {
      uploadedImage = {};
      uploadedImage.iconURL = data.logoURL;
      uploadedImage.fileURL = data.logoURL;
      uploadedImage.thumbnailUrl = data.logoURL;
      uploadedImage.attachmentOID = "logo";
      uploadedImage.fileName = `logo.${data.logoURL.split("/logo/")[1].split("?")[0].split(".")[1] || "png"}`;
    }
    return uploadedImage;
  };

  setLogoImages = () => {
    let uploadedImages = [];
    const uploadedImage = this.getUploadedImage(this.props.tenant);
    if (uploadedImage) {
      uploadedImages = [uploadedImage];
    }
    this.setState({
      uploadedImages,
      showCustomLogo: this.props.tenant.showCustomLogo ? this.props.tenant.showCustomLogo : false,
    });
  };

  hideSetModal = () => {
    this.setState({
      modalIsShow: false,
    });
  };

  setConfirm = () => {
    const uploadedImages = this.state.uploadedImages;
    const { defaultLanguage, supportedLanguages } = this.state;
    if (supportedLanguages.every((item) => !item.enabled)) {
      message.error(messages("basic-1.key7") /*请选择企业支持语言*/);
      return;
    }
    if (!defaultLanguage.code) {
      message.error(messages("basic-1.key8") /*请选择企业默认语言*/);
      return;
    }
    if (uploadedImages.length === 0) {
      DAService.deleteImgId(this.props.tenant.id).then((res) => {
        // 接口设置了租户特性
        // 重新设置一个 redux 控制全局的一些特性
        BaseService.getTenant(this.props.tenant.id);
      });
    }
    const data = {
      tenantId: this.props.tenant.id,
      showCustomLogo: this.state.showCustomLogo,
      tenantLanguageDTO: { defaultLanguage, supportedLanguages },
    };
    DAService.updateTenantInfo(data).then((res) => {
      // 接口设置了租户特性
      // 重新设置一个 redux 控制全局的一些特性
      BaseService.getTenant(res.data.id);
      this.setState({
        modalIsShow: false,
      });
    });
  };

  //是否用自定义logo
  onImageUseChange = (e) => {
    this.setState({
      showCustomLogo: e.target.checked,
    });
  };

  //上传图片后的回调函数
  handleUploadImageChange = (fileList) => {
    fileList.map((item) => {
      item.attachmentOID = item.id;
      item.status = "done";
      item.fileURL = item.logoURL;
      item.fileName = `logo.${item.logoURL.split("/logo/")[1].split("?")[0].split(".")[1] || "png"}`;
    });
    this.setState({
      uploadedImages: fileList,
    });
  };

  onRadioGroupChange = (e) => {
    const { supportedLanguages } = this.state;
    if (e.target.checked) {
      supportedLanguages.forEach((item) => {
        if (item.code === e.target.value) {
          this.setState({
            defaultLanguage: item,
          });
        }
      });
    }
  };

  onCheckboxChange = (e) => {
    const { supportedLanguages, defaultLanguage } = this.state;
    supportedLanguages.forEach((item) => {
      if (item.code === e.target.value) {
        item.enabled = e.target.checked;
      }
      if (e.target.value === defaultLanguage.code && !e.target.checked) {
        this.setState({
          defaultLanguage: {},
        });
      }
    });
    this.setState({
      supportedLanguages,
    });
  };

  render() {
    const { tenant, isDingTalkEnv } = this.props;
    const { modalIsShow, supportedLanguages, defaultLanguage, uploadedImages, showCustomLogo } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16, offset: 1 },
    };
    return (
      <div>
        <Modal
          title={messages("basic-1.key48") /*编辑企业信息*/}
          width={600}
          onCancel={this.hideSetModal}
          visible={modalIsShow}
          onOk={this.setConfirm}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages("basic-1.key55") /*企业名*/}>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{tenant.tenantName}</div>
            </FormItem>
            <FormItem {...formItemLayout} label={messages("basic-1.key56") /*企业LOGO*/}>
              <div className="img-wrap">
                <ImageUpload
                  isShowDefault
                  uploadUrl={`${config.baseUrl}/api/tenant/upload/logo/${tenant.id}`}
                  attachmentType="INVOICE_IMAGES"
                  fileType={["PNG", "png", "JEPG", "jepg", "jpg", "JPG", "bmp", "BMP", "jpg", "JPG", "jpeg", "JPEG"]}
                  defaultFileList={uploadedImages}
                  onChange={this.handleUploadImageChange}
                  maxNum={1}
                  fileUrlKey={"logoURL"}
                />
              </div>
              <div className="img-tips" style={{ color: "#999", fontSize: 13 }}>
                {messages("basic-1.key57") /*建议上传图片尺寸为390*390，大小不超过2M*/}
              </div>
              <div>
                <Checkbox checked={showCustomLogo} onChange={this.onImageUseChange}>
                  {
                    isDingTalkEnv
                      ? messages("basic-1.key58") /*在PC端显示该logo*/
                      : messages("basic-1.key59") /*在APP启动页及PC端显示该logo*/
                  }
                </Checkbox>
              </div>
            </FormItem>
            {supportedLanguages.length ? (
              <FormItem
                {...formItemLayout}
                label={
                  <span>
                    <span style={{ color: "red" }}>*</span>&nbsp;
                    {messages("basic-1.key60") /*企业支持语言*/}
                  </span>
                }
              >
                {supportedLanguages.map((item) => {
                  return (
                    <Checkbox value={item.code} onChange={this.onCheckboxChange} checked={item.enabled}>
                      {item.name}
                    </Checkbox>
                  );
                })}
              </FormItem>
            ) : null}
            {supportedLanguages.length ? (
              <FormItem
                {...formItemLayout}
                label={
                  <span>
                    <span style={{ color: "red" }}>*</span>&nbsp;
                    {messages("basic-1.key61") /*企业默认语言*/}
                  </span>
                }
              >
                <RadioGroup onChange={this.onRadioGroupChange} value={defaultLanguage.code}>
                  {supportedLanguages.map((item) => {
                    return (
                      <Radio value={item.code} disabled={!item.enabled}>
                        {item.name}
                      </Radio>
                    );
                  })}
                </RadioGroup>
                <div className="img-tips" style={{ color: "#999", fontSize: 13 }}>
                  {messages("basic-1.key62") /*企业默认语言必须是企业所支持语言*/}
                </div>
              </FormItem>
            ) : null}
          </Form>
          <div />
        </Modal>
      </div>
    );
  }
}

EditTenantInfo.propTypes = {};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    isDingTalkEnv: state.main.isDingTalkEnv,
  };
}

const wrappedEditTenantInfo = Form.create()(EditTenantInfo);

export default connect(mapStateToProps)(wrappedEditTenantInfo);
